package main.com.cyz.Queue;

import main.com.cyz.Queue.Bean.MyQueue;

import java.util.Iterator;

/**
 * @author fox
 * @version 1.0
 * @description 手写环形数组队列
 * @date 2024/5/19 11:36
 */
public class MyArrayQueue2<E> implements MyQueue<E>,Iterable<E> {

    private E[] array;
    private int head;
    private int tail;
    private int capacity = 8;
    private int size;

    public MyArrayQueue2() {
        array = (E[]) new Object[capacity];
    }

    public MyArrayQueue2(int capacity) {
        this.capacity = capacity;
        array = (E[]) new Object[capacity];
    }

    @Override
    public Iterator<E> iterator() {
        return new Iterator<E>() {

            int point = head;
            int count = 0;

            @Override
            public boolean hasNext() {
                return count < size;
            }

            @Override
            public E next() {
                E value = array[point];
                point = (point + 1) % array.length;
                count ++;
                return value;
            }
        };
    }

    @Override
    public Boolean offer(E value) {
        if (isFull()){
            return false;
        }
        array[tail] = value;
        tail = (tail + 1) % array.length;
        size ++;
        return true;
    }

    @Override
    public E poll() {
        if (isEmpty()){
            return null;
        }
        E value = array[head];
        head = (head + 1) % array.length;
        size --;
        return value;
    }

    @Override
    public E peek() {
        if (isEmpty()){
            return null;
        }
        return array[head];
    }

    @Override
    public Boolean isEmpty() {
        return size == 0;
    }

    @Override
    public Boolean isFull() {
        return size == array.length;
    }
}
